package imdbfolder.gui;

import imdbfolder.data.Movie;
import imdbfolder.gui.icons.IconStore;
import imdbfolder.gui.util.BoldLabel;
import imdbfolder.gui.util.Hyperlink;
import imdbfolder.gui.util.IconLink;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

public class UnknownMoviePanel extends JPanel {

    private static final long serialVersionUID = 1L;

    private UnknownMovieController controller;

    private JPanel workArea;

    private JTextField searchTextField;

    public UnknownMoviePanel(UnknownMovieController controller) {
        this.controller = controller;
    }

    public void initialize() {
        setLayout(new MigLayout("ins 0"));

        add(new BoldLabel("Movie Search:"), "split");

        searchTextField = new JTextField(controller.getSearchString());
        add(searchTextField, "wrap, w 400lp");

        workArea = new JPanel(new MigLayout());

        add(workArea);

        searchTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                controller.setSearchString(searchTextField.getText());
                controller.runSearch(true, false);
            }
        });
    }

    public void setProcessing() {
        workArea.removeAll();

        workArea.add(new JLabel("Fetching movie info.."));

        revalidate();
    }

    public void setPossibleMovies(List<Movie> list) {
        workArea.removeAll();

        if (list.isEmpty()) {
            workArea.add(new JLabel("No movies found!"));
        }
        else {
            for (final Movie movie : list) {
                IconLink acceptIcon = new IconLink(IconStore.get("accept.png"));
                acceptIcon.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        controller.selectMovie(movie);
                    }
                });

                workArea.add(acceptIcon);

                workArea.add(new Hyperlink(movie.getImdbId(), movie.getImdbUrl()));

                workArea.add(new JLabel(movie.getTitle() + " (" + movie.getYear() + ")"), "wrap");
            }
        }

        workArea.revalidate();
    }
}
